import { db } from "@/db";
import { tasks } from "@/db/schema";
import { baseProcedure, createTRPCRouter, protectedProcedure } from "@/trpc/init";
import { eq } from "drizzle-orm";
import { z } from "zod";
// 定义任务创建输入参数的验证规则
const createTaskSchema = z.object({
  name: z.string().min(1, "任务名称不能为空"),
  description: z.string().optional(),
  priority: z.enum(["low", "medium", "high"]).default("medium"),
  status: z.enum(["todo", "in_progress", "done"]).default("todo"),
  // 不需要在输入中包含id，数据库会自动生成
  // userId可以从ctx中获取，也不需要客户端传递
});

// 更新任务输入参数验证规则
const updateTaskSchema = z.object({
  id: z.number(),
  name: z.string().min(1, "任务名称不能为空"),
  description: z.string().optional(),
  priority: z.enum(["low", "medium", "high"]).default("medium"),
  status: z.enum(["todo", "in_progress", "done"]).default("todo"),
  // userId可以从ctx中获取，也不需要客户端传递
})

const delTaskSchema = z.object({
  id: z.number(),
});
export const createTasksRouter = createTRPCRouter({
  getMany: protectedProcedure.query(async ({ctx}) => {
    const { user  } = ctx;
    const data = await db.select().from(tasks);
    return data;
  }),

  create: protectedProcedure
    .input(createTaskSchema) // 使用定义好的schema验证输入
    .mutation(async ({ ctx, input }) => {
      // 从上下文中获取用户ID（假设你的认证中间件已经添加了userId）
      const { user  } = ctx;
      const newTask = await db.insert(tasks).values({
        name: input.name,
        description: input.description,
        priority: input.priority,
        status: input.status,
        userId: user?.id ?? '', // 使用从上下文中获取的用户ID
      })

      return newTask
    }),
  delete: baseProcedure.input(z.object({ id: z.number() })).mutation(async ({ input }) => {
    const data = await db.delete(tasks).where(eq(tasks.id, input.id)).returning();
    return {
      success: true,
      data: data[0],
    };
  }),
  // 更新
  update: baseProcedure.input(updateTaskSchema).mutation(async ({input}) => {
    await db.update(tasks)
    .set({ 
      name: input.name,
      description: input.description,
      priority: input.priority,
      status: input.status,
    })
    .where(eq(tasks.id, input.id))
    .execute();
  }),
});